<template>
    <view class="user-dynamic">
        <!-- 选项卡 -->
        <view class="dynamic-list">
            <text
                v-for="item in dynamicList"
                :key="item.id"
                :class="['item-label', { active: activeTab === item.value }]"
                @click="switchTab(item.value)"
            >
                {{ item.label }}
            </text>
        </view>

        <!-- 内容区域 -->
        <view class="dynamic-content">
            <template v-for="tab in dynamicList" :key="tab.id">
                <dynamic-content
                    v-if="activeTab === tab.value"
                    :content="getContentData(tab.value)"
                    :emptyText="tab.emptyText"
                    :showPublishButton="tab.showPublishButton"
                    @navigateToPublish="navigateToPublish"
                    @previewImage="previewImage"
                />
            </template>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { USER_DYNAMIC_LIST, POST_STATUS } from '@/util/config/user.config.js';
import { usePostStore } from '@/stores/postStores';
import { useUserStore } from '@/stores/userStores';

import dynamicContent from './dynamicContent.vue';

const activeTab = ref('works');
const postStore = usePostStore();
const userStore = useUserStore();
const userId = userStore.currentUser.userId;

// 配置选项卡
const dynamicList = ref(USER_DYNAMIC_LIST);
// 根据选项卡映射帖子状态
const statusMap = POST_STATUS;

// 初始化帖子数据
onMounted(async () => {
    // 初始化用户数据
    await userStore.init();

    // 防止刷新数据缺失，在这里获取用户 id
    const userId = userStore.currentUser.userId;

    // 初始化帖子数据
    await postStore.init();

    // 获取用户帖子
    await postStore.getPostsByUserId(userId);
});

// 动态获取内容数据
const getContentData = (tabValue) => {
    const status = statusMap[tabValue];
    return postStore.getPostsByStatus(status) || [];
};

// 切换选项卡
const switchTab = (tabValue) => {
    activeTab.value = tabValue;
};

// 跳转到发布页
const navigateToPublish = () => {
    uni.navigateTo({
        url: '/pages/user/subpages/post/post'
    });
};
</script>

<style scoped lang="scss">
.user-dynamic {
    position: relative;
    .dynamic-list {
        position: sticky;
        top: 0;
        z-index: 999;
        background: $han-global-bg-color;
        display: flex;
        justify-content: space-around;

        .item-label {
            width: 160rpx;
            text-align: center;
            color: $han-global-secondary-font-color;
            padding-bottom: 8rpx;
            border-bottom: 4rpx solid transparent; /* 初始透明边框 */

            &.active {
                color: $han-primary-color;
                border-bottom: 4rpx solid $han-primary-color;
            }
        }
    }
}
</style>
